<template>
  <div class="app-container">
    <el-form :model="queryParam" ref="queryForm" :inline="true">
      <el-form-item label="学科：">
        <el-select v-model="queryParam.subjectId" clearable>
          <el-option
            v-for="item in subjects"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="姓名：">
        <el-input v-model="queryParam.realName" />
      </el-form-item>

      <el-form-item label="手机号：">
        <el-input v-model="queryParam.userName" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="exportExcle">导出</el-button>
      </el-form-item>
    </el-form>
    <div class="custom-thead">
      <input type="checkbox" v-model="allSelected" @change="handleAllSelect" />
      <span></span>
    </div>
    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      :data="tableData"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column label="" width="55" align="center">
        <template slot-scope="scope">
          <input
            type="checkbox"
            :value="scope.$index"
            v-model="scope.row.check"
            @change="handleRowSelect(scope.$index, scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="id" label="Id" width="100" />
      <el-table-column prop="paperName" label="试卷名称" />
      <el-table-column prop="userName" label="用户名称" />
      <el-table-column prop="realName" label="真实姓名" />

      <el-table-column label="得分" width="100px">
        <template slot-scope="{ row }">
          {{ row.userScore }} / {{ row.paperScore }}
        </template>
      </el-table-column>
      <el-table-column label="题目对错" width="80px">
        <template slot-scope="{ row }">
          {{ row.questionCorrect }} / {{ row.questionCount }}
        </template>
      </el-table-column>
      <el-table-column prop="doTime" label="耗时" width="100px" />
      <el-table-column prop="createTime" label="提交时间" width="160px" />
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParam.pageIndex"
      :limit.sync="queryParam.pageSize"
      @pagination="search"
    />
  </div>
</template>

<script>
import XLSX from "xlsx";
import { saveAs } from "file-saver";
import { mapGetters, mapState, mapActions } from "vuex";
import Pagination from "@/components/Pagination";
import examPaperAnswerApi from "@/api/examPaperAnwser";

export default {
  components: { Pagination },
  data() {
    return {
      selectList: [],
      isIndeterminate: false,
      allSelected: false,
      checkidList: [],
      queryParam: {
        subjectId: null,
        pageIndex: 1,
        realName:'',
        telnum:'',
        pageSize: 10,
      },
      selectedRows: [],
      listLoading: false,
      tableData: [],
      total: 0,
    };
  },
  created() {
    this.initSubject();
    this.search();
    const savedSelection = localStorage.getItem("selectedTableRows");
    if (savedSelection) {
      this.selectedRows = JSON.parse(savedSelection);
    }
  },
  watch: {
    tableData: {
      handler(newData) {
        // 当tableData变化时（如分页切换），尝试根据已选中的ID重新设置选中状态
        setTimeout(() => {
          this.restoreSelection(newData);

          // this.checkidList.push(this.selectedRows)
        }, 1000);
      },
      deep: true,
    },
    selectedRows: {
      handler(newData) {
        //   this.checkidList = new Set(newData)
        //   console.log( this.checkidList);
        // localStorage.setItem('checkidList', JSON.stringify(Array.from(this.checkidList)));
      },
      deep: true,
    },
    queryParam: {
      handler(newData) {},
      deep: true,
    },
  },
  methods: {
    downloadBlob(blob, fileName) {
      // 创建隐藏的可下载链接
      var url = window.URL.createObjectURL(blob);
      var a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      a.download = fileName;
      document.body.appendChild(a);
      
      // 触发点击
      a.click();
      
      // 清理
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    },
    // 导出按钮
    exportExcle() {
      // this.queryParam.pageIndex =-1
      // this.queryParam.pageSize =-1
      if(this.checkidList.length==0){
        return this.$message.warning("请选择要导出的数据!")
      }
      const filteredAndStringifiedArray = this.checkidList
        // 过滤掉空值
        .filter((item) => item !== undefined)
        // 将剩余的数字转换为字符串
        .map(String);
      examPaperAnswerApi.download(filteredAndStringifiedArray).then((response) => {
        console.log(response);
        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' });
    const fileName = '考试数据.xlsx';
        this.downloadBlob(response,fileName)
      });
      return;
      // 获取表格的DOM元素
      const ws = XLSX.utils.table_to_sheet(
        this.$refs.exportTable.$el.querySelector("table")
      );

      // 创建工作簿
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

      // 导出Excel
      const wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        saveAs(new Blob([wbout], "表格数据.xlsx"));
        this.checkidList = []
      } catch (e) {
        console.error(e);
      }
    },

    handleRowSelect(index, row) {
      const isSelected = this.selectedRows.includes(index);

      // 更新selectedRows
      if (isSelected) {
        this.selectedRows = this.selectedRows.filter((i) => i !== index);
      } else {
        this.selectedRows.push(index);
      }

      this.updateAllSelectedStatus();

      // 使用Set去重并管理checkidList
      let idSet = new Set(this.checkidList); // 将现有列表转换为Set

      // 根据row.check的状态增删元素
      if (row.check) {
        idSet.add(row.id);
      } else {
        idSet.delete(row.id);
      }

      // 将Set转回Array
      this.checkidList = Array.from(idSet);

      console.log(this.checkidList);
    },
    // allSelected(){

    // },
    updateAllSelectedStatus(data) {
      this.allSelected = this.selectedRows.length === this.tableData.length;
      this.isIndeterminate = this.selectedRows.length > 0 && !this.allSelected;
    },
    // 全选
    handleAllSelect(event) {
      console.log("全选执行");
      this.tableData = this.tableData.map((row) => ({
        ...row,
        check: event.target.checked,
      }));

      // 获取当前页所有行的ID
      const currentIds = this.tableData.map((row) => row.id);

      // 根据全选状态处理checkidList
      if (event.target.checked) {
        // 如果全选，检查当前页的ID是否已经全部在checkidList中，缺失的添加
        currentIds.forEach((id) => {
          if (!this.checkidList.includes(id)) {
            this.checkidList.push(id);
          }
        });
      } else {
        // 如果取消全选，从checkidList中移除当前页的所有ID
        this.checkidList = this.checkidList.filter(
          (id) => !currentIds.includes(id)
        );
      }

      console.log(this.checkidList);
    },
    restoreSelection(tempSelectedRows) {
      // 根据新的数据集来恢复或初始化选中状态
      // 假设 this.tableData 已经包含了新加载的数据
      const allSelectedIds = new Set(
        JSON.parse(localStorage.getItem("checkidList") || "[]")
      );
      const currentIds = new Set(this.tableData.map((row) => row.id)); // 当前页面所有行的ID
      const validSelectedIds = new Set(
        [...allSelectedIds].filter((id) => currentIds.has(id))
      ); // 当前页面中有效的已选ID

      // 如果有临时保存的选中状态（比如，从其他页面返回时），优先恢复这些选中状态
      if (tempSelectedRows && tempSelectedRows.length) {
        validSelectedIds.forEach((id) => {
          const row = this.tableData.find((item) => item.id === id);
          if (row) {
            this.$refs.multipleTable.toggleRowSelection(row, true);
          }
        });
      } else {
        // 否则，根据全局存储的状态来恢复
        validSelectedIds.forEach((id) => {
          const row = this.tableData.find((item) => item.id === id);
          if (row) {
            this.$refs.multipleTable.toggleRowSelection(row, true);
          }
        });
      }

      // 更新或初始化selectedRows，注意这里根据逻辑调整
      this.selectedRows = Array.from(validSelectedIds); // 或者根据需求决定是否使用tempSelectedRows

      // 保持localStorage与selectedRows同步
      localStorage.setItem(
        "selectedTableRows",
        JSON.stringify(Array.from(this.selectedRows))
      );
    },
    handleSelectionChange(data) {
      // 获取当前选中行的ID集合
      const newSelectedIds = data
        .filter(
          (row) =>
            row !== undefined &&
            typeof row === "object" &&
            row.hasOwnProperty("id")
        )
        .map((row) => row.id);

      // 从localStorage获取之前的选中行id（如果有的话），并转为Set方便操作
      let prevSelectedIds = new Set(
        JSON.parse(localStorage.getItem("selectedTableRows") || "[]")
      );

      // 计算本次选中与上次选中的差异
      const addedIds = new Set(
        [...newSelectedIds].filter((id) => !prevSelectedIds.has(id))
      ); // 新增的ID
      const removedIds = new Set(
        [...prevSelectedIds].filter((id) => !newSelectedIds.includes(id))
      ); // 被移除的ID

      removedIds.forEach((id) => prevSelectedIds.delete(id));
      addedIds.forEach((id) => prevSelectedIds.add(id));

      this.selectedRows = Array.from(prevSelectedIds);
      localStorage.setItem(
        "selectedTableRows",
        JSON.stringify(this.selectedRows)
      );
    },

    search() {
      this.listLoading = true;
      examPaperAnswerApi.page(this.queryParam).then((data) => {
        const re = data.response;
        this.tableData = re.list;
        this.total = re.total;
        this.queryParam.pageIndex = re.pageNum;
        this.listLoading = false;
        this.tableData = this.tableData.map((res) => {
          let isChecked = this.checkidList.includes(res.id);
          return {
            ...res,
            check: isChecked, // 直接根据 checkidList 决定 check 属性的值
          };
        });
      });
    },
    recoverSelectionOnCurrentPage(prevSelectedIds) {
      // 仅针对当前页面数据恢复选中
      const currentIds = new Set(this.tableData.map((row) => row.id));
      const validSelectedIds = new Set(
        [...prevSelectedIds].filter((id) => currentIds.has(id))
      );

      // 更新表格的选中状态
      validSelectedIds.forEach((id) => {
        const row = this.tableData.find((item) => item.id === id);
        if (row) {
          this.$refs.multipleTable.toggleRowSelection(row, true);
        }
      });
    },
    submitForm() {
      this.queryParam.pageIndex = 1;
      this.search();
    },
    ...mapActions("exam", { initSubject: "initSubject" }),
  },
  computed: {
    ...mapGetters("enumItem", ["enumFormat"]),
    ...mapGetters("exam", ["subjectEnumFormat"]),
    ...mapState("exam", { subjects: (state) => state.subjects }),
  },
};
</script>
<style scoped>
.custom-thead {
  display: flex;
  align-items: center;
  padding: 10px 0;
  /* border-bottom: 1px solid #ddd;   */
  position: relative;
  bottom: -39px;
  z-index: 99;
  right: -20px;
}
.custom-thead input[type="checkbox"] {
  margin-right: 5px;
}
</style>
